import { useMutation, useQuery } from "@apollo/client";
import {
  commitCard_service,
  deleteCard_service,
  getCards_service,
} from "../../graphql/cards";
import { cardType } from "../../pages/course/cpms/card/config";
import { message } from "antd";

export const useFetch_getCards = (courseId?: string, name?: string) => {
  const {
    data,
    loading,
    refetch,
  }: {
    data: { getCards: { data: cardType[] } };
    loading: boolean;
    refetch: (options: any) => void;
  } = useQuery(getCards_service, {
    variables: {
      courseId,
      name,
    },
  }) as {
    data: { getCards: { data: cardType[] } };
    loading: boolean;
    refetch: (options: any) => void;
  };
  return {
    refetch,
    data: data ? data.getCards.data : [],
    getLoading: loading,
  };
};

export const useFetch_commitCard = () => {
  const [commit, { loading }] = useMutation(commitCard_service);

  const commitCard = async (
    crouseId: string,
    params: Partial<cardType>,
    id?: string
  ): Promise<void> => {
    const data = await commit({
      variables: {
        crouseId,
        params,
        id: id === "new" ? undefined : id,
      },
    });
    void message.success(data.data.commitCardInfo.message);
  };
  return { commitCard, commitLoading: loading };
};

export const useDeleteCard = () => {
  const [del, { loading }] = useMutation(deleteCard_service);

  const deleteCard = async (id: string) => {
    const data = await del({
      variables: {
        id: id,
      },
    });
    void message.success(data.data.deleteCard.message);
  };

  return {
    deleteCard,
    delLoading: loading,
  };
};
